package com.yy.util;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/*
 * 用于检测用户是否登陆的过滤器，如果未登陆或超时，则重新返回登陆jie'm
 * 
 * */
public class SessionFilterUtil implements Filter{
	public void doFilter(ServletRequest servletRequest,ServletResponse servletResponse,
			FilterChain filterChain)throws IOException,ServletException{
		
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		HttpServletResponse response = (HttpServletResponse) servletResponse;
		
		String currentURL = request.getRequestURI();								//获取根目录所对对应的绝对路径
		System.out.println("THIS is current URL------>+"+currentURL);
		String checkURL = currentURL.substring(currentURL.lastIndexOf("/"), currentURL.length());
		
		HttpSession session = request.getSession(false);
		String type = request.getHeader("X-Requested-With");
		System.out.println("this is checkURL------->"+checkURL);
		try{
			if(!"/loginCheck.action".equals(checkURL)){
				System.out.println("*******链接不是logincheck.action*****************");
				if((session == null) || (session.getAttribute("loginusersession") == null)){
					if ("XMLHttpRequest".equalsIgnoreCase(type)){
						System.out.println("aaaaaaaaaaaaaaaaa");
						response.setHeader("sessionstatus", "sessiontimeout");
						//response.sendRedirect("../NewFile.html");
						System.out.println("bbbbbbbbbbbbbbbbbbb");
						return ;
					}
					else{
						System.out.println("hhhhhhhhhhhhhhhhhhh");
						//response.sendRedirect("../NewFile.html");
						response.setHeader("sessionstatus", "nosession");
						return ;
					}
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
		}
		
		filterChain.doFilter(request, response);
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
		
	}
}
